package com.jackrain.nea.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.shiro.stateful.CustomizedToken;
import com.jackrain.nea.shiro.stateful.LoginType;
import com.jackrain.nea.web.common.Handle;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySession;
import com.jackrain.nea.web.query.QueryUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by nathan on 2016/10/12.
 */
public class TryLoginUtil {

    public final Logger logger = Logger.getLogger(TryLoginUtil.class);

    /**
     *
     * 用来判断是否登录成功
     * @param username
     * @param password
     * @param loginType
     * @param rememberMe
     * @return
     */
    public boolean tryLogin(String username, String password, LoginType loginType, boolean rememberMe, Subject subject, String IP){
        if(!subject.isAuthenticated()){
            CustomizedToken token = new CustomizedToken(username,password,loginType,rememberMe,IP);
            try {
                subject.login(token);//登录验证\
                HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

                User userWeb = (User) subject.getPrincipal();
                logLogin(userWeb,WebUtils.getIpAddress(request),request.getHeader("User-Agent"),request,"login");
                return true;
            }catch (UnknownAccountException uae) {
                System.out.println("No User Found" + token.getPrincipal());
                logger.error("没有根据用户名找到用户" + uae.getMessage());
            }catch (IncorrectCredentialsException ice){
                System.out.println("Password for account"+token.getPrincipal());
                logger.error("密码无效" + ice.getMessage());
            }catch (LockedAccountException lae){
                System.out.println("blocked"+token.getPrincipal());
                logger.error("锁"+lae.getMessage());
            }catch (AuthenticationException ae){
                System.out.println("User cannot be authenticated"+token.getPrincipal());
                logger.error("用户不能被鉴定"+ae.getMessage());
            }
        }else {
            return true;
        }
        return false;
    }


    public void logLogin(final User user,final String host,final String message,final HttpServletRequest request,final String subModule){
        ExecutorService executorService = new ThreadPoolExecutor(1,10,3000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                JSONObject jo=new JSONObject();
                jo.put("objid",-1);
                JSONObject fixcolumn=new JSONObject();
                JSONObject log=new JSONObject();
                log.put("SUBMODULE",subModule);
                log.put("OPERATOR",user.getName());
                log.put("REMOTE_HOST",host);
                log.put("MESSAGE",message);
                log.put("CREATIONDATE",new Date());
                log.put("AD_CLIENT_ID",user.getClientId());
                JSONObject[] logs = {log};
                fixcolumn.put("C_SYSLOG",logs);
                jo.put("fixcolumn",fixcolumn);
                jo.put("table","C_SYSLOG");
                QuerySession qsession = QueryUtils.createQuerySession(user);
                DefaultWebEvent event = new DefaultWebEvent("doSave", request, false);

                event.put("param", jo);

                Handle handle=ApplicationContextHandle.getBean(Handle.class);
                try {
                    handle.process(jo,qsession,event,"save");
                } catch (Exception e) {
                    logger.error("记录用户登录日志失败，"+ JSON.toJSONString(jo),e);
                }
            }
        });

    }
}
